﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsProject.utils
{
    public class HttpHelper
    {
        private readonly HttpClient _httpClient;

        // 构造函数：支持自定义 HttpClient 或使用默认配置
        public HttpHelper(HttpClient httpClient = null)
        {
            _httpClient = httpClient ?? new HttpClient();
        }

        /// <summary>
        /// 发送 GET 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">自定义请求头（可选）</param>
        /// <returns>响应内容（字符串）</returns>
        public async Task<string>  GetAsync(string url, WebHeaderCollection headers = null)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                AddHeaders(request, headers);

                HttpResponseMessage response = await _httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode(); // 确保状态码为 2xx
                byte[] bytes = await response.Content.ReadAsByteArrayAsync();
                return Encoding.UTF8.GetString(bytes);
            }
            catch (HttpRequestException ex)
            {
                throw new WebException($"GET请求失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 发送 POST 请求（JSON 格式）
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="jsonData">JSON 字符串数据</param>
        /// <param name="headers">自定义请求头（可选）</param>
        public async Task<string> PostJsonAsync(string url, string jsonData, WebHeaderCollection headers = null)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                if ( !string.IsNullOrEmpty(jsonData) ) {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    request.Content = content;
                }
                AddHeaders(request, headers);

                HttpResponseMessage response = await _httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode();
                byte[] bytes = await response.Content.ReadAsByteArrayAsync();
                return Encoding.UTF8.GetString(bytes);
            }
            catch (HttpRequestException ex)
            {

                return $"POST请求失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 添加自定义请求头
        /// </summary>
        private void AddHeaders(HttpRequestMessage request, WebHeaderCollection headers)
        {
            if (headers == null) return;
            foreach (string key in headers)
            {
                request.Headers.Add(key, headers[key]);
            }
        }

        /// <summary>
        /// 设置超时时间（秒）
        /// </summary>
        public void SetTimeout(int seconds)
        {
            _httpClient.Timeout = TimeSpan.FromSeconds(seconds);
        }

    }
}
